package com.defysoft.waukids.calendar;

import java.util.ArrayList;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukids.BaseActivity;
import com.defysoft.waukids.Custom_Data_Type;
import com.defysoft.waukids.Custom_Data_Type.WK_CLASS_NAME_LIST;
import com.defysoft.waukids.Custom_Data_Type.WK_STUDENT_ATTEND_LIST;
import com.defysoft.waukids.Data_Sharedpreferences;
import com.defysoft.waukids.JsonParser;
import com.defysoft.waukids.PublicConstant;
import com.defysoft.waukids.PublicSharedpreferences;
import com.defysoft.waukids.R;
import com.defysoft.waukids.Sqlite_Connect;

public class CalendarAttendListActivity extends BaseActivity{
	View view;
	ListView listView;
	Toolbar toolbar;
	Spinner spinner;
	TextView title;
	PublicSharedpreferences psf;
	Data_Sharedpreferences.SF_Member member;
	ArrayList<WK_STUDENT_ATTEND_LIST> attendList;
	ArrayList<WK_CLASS_NAME_LIST> classNameList;
	Sqlite_Connect sqlite_Connect;
	int list_count = 0;
	Calendar_Attend_List_Adapter adapter;
	String Att_Date, FK_Stu_Att_Code, Att_Reason, Att_Check  = "";
	int chang_pos = 0;
	String choice_class;	//스피너에서 선택한 반
	String reason_change;
	private final int LIST_THREAD = 0;
	private final int SUCCESS_LIST = 1;
	private final int FAIR_LIST = 2;
	private final int ATTEND_INSERT_THREAD = 3;
	private final int SUCCESS_INSERT = 4;
	private final int FAIR_INSERT = 5;
	private final int ATTEND_CHANGE_THREAD = 6;
	private final int SUCCESS_CHANGE = 7;
	private final int FAIR_CHANGE = 8;
	private final int SPINNER_LIST_THREAD = 9;
	private final int SUCCESS_SPINNER_LIST = 10;
	private final int FAIR_SPINNER_LIST = 11;
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.calendar_attend_list_a);
		Att_Date = getIntent().getStringExtra("Att_Date");
		//Att_Date = "2015-01-29";
		setStartData();
		setStartToolbar();
	}

	@Override
	public void setStartData() {
		super.setStartData();
		psf = new PublicSharedpreferences(this);
		psf.setMembersp();
		member = psf.getMembersp();
		sqlite_Connect = new Sqlite_Connect(this);
		//임시저장.
		/*member.Rank = "1";
		member.School = "45";
		member.Class = "33";*/

		attendList = new ArrayList<Custom_Data_Type.WK_STUDENT_ATTEND_LIST>();
		classNameList = new ArrayList<Custom_Data_Type.WK_CLASS_NAME_LIST>();
		listView = (ListView)findViewById(R.id.CALENDAR_ATTEND_LIST_LISTVIEW);
		toolbar = (Toolbar)findViewById(R.id.CALENDAR_ATTEND_LIST_TOOLBAR);
		spinner = (Spinner)findViewById(R.id.CALENDAR_ATTEND_LIST_SPI);
		title = (TextView)findViewById(R.id.CALENDAR_ATTEND_LIST_TITLE);

		if (member.Rank.equals("1")) {
			spinner.setVisibility(View.VISIBLE);
		}
		
		startNetwork(LIST_THREAD);
	}
	
	private void setStartToolbar() {
		toolbar.setNavigationOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				alertDialogSetResult("출석체크를 종료하겠습니까?", REFRESH_CODE);
			}
		});
		spinner.setAdapter(new ArrayAdapter<String>(this, 0) {
			@Override
			public int getCount() {
				return classNameList.size();
			}

			@Override
			public View getDropDownView(int position, View convertView,
					ViewGroup parent) {
				final int pos = position;
				if (convertView == null) {
					convertView = getLayoutInflater().inflate(
							R.layout.overflowitem_row, null);
				}
				((TextView) convertView.findViewById(R.id.OVERFLOWITEM_TV))
						.setText(classNameList.get(pos).Cla_Name);
				convertView.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						choice_class = classNameList.get(pos).PK_Cla_Code;
						
						startNetwork(SPINNER_LIST_THREAD);						
					}
				
				});
				return convertView;
			}

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				final int pos = position;
				if (convertView == null) {
					convertView = getLayoutInflater().inflate(
							R.layout.overflowitem_row, null);
				}
				((TextView) convertView.findViewById(R.id.OVERFLOWITEM_TV))
						.setBackgroundColor(0x00ffffff);
				return convertView;
			}
		});
	}	
	
	@Override
	public void startThread(int choice) {
		// TODO Auto-generated method stub
		super.startThread(choice);
		if (firstThread != null) {
			firstThread.interrupt();
		}
		final int cho = choice;
		firstThread = new Thread(new Runnable() {
			@Override
			public void run() {
				switch (cho) {
				case LIST_THREAD:
					listThread();
					break;
				case ATTEND_INSERT_THREAD:
					attendInsertThread();
					break;
				case ATTEND_CHANGE_THREAD:
					attendChangeThread();
					break;
				case SPINNER_LIST_THREAD:
					spinnerListThread();
					break;

				}
			}
		});
		firstThread.start();

	}



	protected void spinnerListThread() {
		JSONObject jsonObject = null;
		
		try {
				jsonObject = new JSONObject(publicHttpCallback(HTTP_URL,
						"code=" + CODE_CALENDAR_ATTEND_LIST_LOAD 
						+ "&FK_Sch_Mem_Code=" + member.School
						+ "&FK_Cla_Mem_Code=" +  choice_class
						+ "&Att_Date=" + Att_Date));
				if (jsonObject.getBoolean("success")) {
					attendList = new ArrayList<Custom_Data_Type.WK_STUDENT_ATTEND_LIST>();
					attendList = JsonParser.Calendar_Attend_Student_List(jsonObject.getString("payload"));
					
					this.list_count = jsonObject.getInt("count");
					onNetworkCallback(SUCCESS_SPINNER_LIST, "");
				} else {
					onNetworkCallback(FAIR_SPINNER_LIST, jsonObject.getString("message"));
					}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString()+" where spinnerListThread()");
			}
	}


	protected void attendInsertThread() {
		JSONObject jsonObject = null;
		try {
			if (member.Rank.equals("2")) { // 선생님.
				jsonObject = new JSONObject(publicHttpCallback(HTTP_URL,
						"code=" +CODE_CALENDAR_ATTEND_LIST_INSERT
						+ "&FK_Sch_Att_Code=" + member.School
						+ "&FK_Cla_Att_Code=" + member.Class
						+ "&FK_Stu_Att_Code=" + FK_Stu_Att_Code
						+ "&Att_Date=" +  Att_Date
						+ "&Att_Reason=" +  "출석" ));
				if (jsonObject.getBoolean("success")) {
					onNetworkCallback(SUCCESS_INSERT, "");
				} else {
					onNetworkCallback(FAIR_INSERT, jsonObject.getString("message"));
					}

			} else if (member.Rank.equals("1")) { // 원장선생님.
				jsonObject = new JSONObject(publicHttpCallback(HTTP_URL,
						"code=" +CODE_CALENDAR_ATTEND_LIST_INSERT
						+ "&FK_Sch_Att_Code=" + member.School
						+ "&FK_Stu_Att_Code=" + FK_Stu_Att_Code
						+ "&Att_Date=" +  Att_Date
						+ "&Att_Reason=" +  "출석"));
				if (jsonObject.getBoolean("success")) {
					onNetworkCallback(SUCCESS_INSERT, "");
				} else {
					onNetworkCallback(FAIR_INSERT, jsonObject.getString("message"));
					}
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString()+" where attendInsertThread()");
			}
	}


	protected void listThread() {
		JSONObject jsonObject = null;
		try {
			if (member.Rank.equals("2")) { // 선생님.
				jsonObject = new JSONObject(publicHttpCallback(HTTP_URL,
						"code=" + CODE_CALENDAR_ATTEND_LIST_LOAD 
						+ "&FK_Sch_Mem_Code=" + member.School
						+ "&FK_Cla_Mem_Code=" +  member.Class
						+ "&Att_Date=" + Att_Date));
				if (jsonObject.getBoolean("success")) {
					attendList = JsonParser.Calendar_Attend_Student_List(jsonObject.getString("payload"));
					this.list_count = jsonObject.getInt("count");
					onNetworkCallback(SUCCESS_LIST, "");
				} else {
					onNetworkCallback(FAIR_LIST, jsonObject.getString("message"));
					}

			} else if (member.Rank.equals("1")) { // 원장선생님.
				jsonObject = new JSONObject(publicHttpCallback(HTTP_URL,
						"code=" + CODE_CALENDAR_ATTEND_LIST_LOAD 
						+ "&FK_Sch_Mem_Code=" + member.School 
						+ "&Att_Date=" + Att_Date));
				if (jsonObject.getBoolean("success")) {
					attendList = JsonParser.Calendar_Attend_Student_List(jsonObject.getString("payload"));
					this.list_count = jsonObject.getInt("count");
					this.classNameList = JsonParser.calendar_class_name_list(jsonObject.getString("classname"));
					onNetworkCallback(SUCCESS_LIST, "");
				} else {
					onNetworkCallback(FAIR_LIST, jsonObject.getString("message"));
					}

			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString()+" where listThread()");
			}
	}
	
	protected void attendChangeThread() {
		String msg = "";
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(HTTP_URL,
					"code=" + CODE_CALENDAR_ATTEND_LIST_ATTEND_CHANGE 
					+ "&FK_Stu_Att_Code=" + FK_Stu_Att_Code
					+ "&Att_Check=" + Att_Check
					+ "&Att_Date=" + Att_Date
					+ "&Att_Reason=" + Att_Reason));
			if (jsonObject.getBoolean("success")) {
				reason_change = jsonObject.getString("reason");
				onNetworkCallback(SUCCESS_CHANGE, jsonObject.getString("payload"));
			} else {
				onNetworkCallback(FAIR_CHANGE, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString()+" where attendChangeThread()");
		}
	}

	
	@Override
	protected void handlingMessage(Message _message) {
		super.handlingMessage(_message);
		switch (_message.what) {
		case SUCCESS_LIST:
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}			
			adapter = new Calendar_Attend_List_Adapter();
			listView.setAdapter(adapter);
			if (member.Rank.equals("1")) {
				title.setText(Att_Date+"\n"+attendList.get(0).cla_name+" 출결현황");
			} else if (member.Rank.equals("2")) {
				title.setText(Att_Date+"\n"+attendList.get(0).cla_name+" 출결현황");
			}
			break;
			
		case FAIR_LIST:
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}		
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT).show();
			break;
			
		case SUCCESS_INSERT:
			endDIal();
			attendList.get(chang_pos).check = "0";
			adapter.notifyDataSetChanged();
			
			break;
			
		case FAIR_INSERT:
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}		
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT).show();
			break;

		case SUCCESS_CHANGE:	//check값 가져오기.
			endDIal();
			attendList.get(chang_pos).check = (String)_message.obj;
			attendList.get(chang_pos).reason = reason_change;
			adapter.notifyDataSetChanged();

			break;
			
		case FAIR_CHANGE:
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}		
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT).show();
			break;
			
		case SUCCESS_SPINNER_LIST:
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}	
			//adapter = new Calendar_Attend_List_Adapter();
			listView.setAdapter(adapter);
			//spinner_adapter =new Calendar_Spinner_List_Adapter();
			//spinner.setAdapter(spinner_adapter);
			break;
			
		case FAIR_SPINNER_LIST:
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}		
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT).show();
			break;
			
		case CATCH_EXCEPTION:
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}					
			sqlite_Connect.insert_Err_Log((String)_message.obj,android.os.Build.VERSION.SDK_INT,"CalendatAttendListActivity", member.Email);
			break;

		default:
			break;
		}
	}
	

	class Calendar_Attend_List_Adapter extends ArrayAdapter<String> {
		public Calendar_Attend_List_Adapter() {
			super(CalendarAttendListActivity.this, 0);
		}
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return attendList.size();
		}
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			Calendar_Attend_List_Holder holder;
			final int pos = position;
			if (convertView == null) {
				convertView = CalendarAttendListActivity.this.getLayoutInflater()
						.inflate(R.layout.calendar_attend_list_row, null);
				holder = new Calendar_Attend_List_Holder();
				holder.student_name = (TextView) convertView.findViewById(R.id.CALENDAR_ATTEND_LIST_ROW_NAME);
				holder.image = (WebView) convertView.findViewById(R.id.CALENDAR_ATTEND_LIST_ROW_IMG);
				holder.newcheck = (ImageView) convertView.findViewById(R.id.CALENDAR_ATTEND_LIST_ROW_ATTEND);
				holder.linearLayout = (LinearLayout) convertView.findViewById(R.id.CALENDAR_ATTEND_LIST_ROW_LL);
				holder.textViewReason = (TextView) convertView.findViewById(R.id.CALENDAR_ATTEND_LIST_ROW_REASON);
				convertView.setTag(holder);
			} else {
				holder = (Calendar_Attend_List_Holder) convertView.getTag();
			}
			//원생이름
			holder.student_name.setText(attendList.get(position).Stu_Name);
			//원생사진
			holder.image.setVerticalScrollBarEnabled(false);
			holder.image.setVerticalScrollbarOverlay(false);
			holder.image.setHorizontalScrollBarEnabled(false);
			holder.image.setHorizontalScrollbarOverlay(false);
			holder.image.setInitialScale(100);
			if ( attendList.get(position).Stu_Photo == null||attendList.get(position).Stu_Photo.length()<5) {// 이미지 파일이 없으면 앱내에서 지정된 이미지를 뿌려주고
				holder.image.setBackgroundColor(0);
				holder.image.setBackgroundResource(R.drawable.photo_two);
			} else {// 이미지 파일이 있으면
				holder.image.loadDataWithBaseURL(null,
						creHtmlBody(PublicConstant.HTTP_URL_STUDENTPHOTO
								+ attendList.get(position).Stu_Photo), "text/html", "utf-8", null);
			}
			Log.i("attendList.get(pos).reason=", attendList.get(position).reason);
			//원생출석,결석이미지
			if (attendList.get(position).check.equals("null")) {
				holder.student_name.setTextColor(0xff58595b);
				holder.linearLayout.setBackgroundResource(R.drawable.attenditem_false);
				holder.newcheck.setBackgroundResource(R.drawable.icon);
			} else if (attendList.get(position).check.equals("0")) {
				holder.student_name.setTextColor(0xff58595b);
				holder.linearLayout.setBackgroundResource(R.drawable.attenditem_false);
				holder.newcheck.setBackgroundResource(R.drawable.check_on);
				holder.textViewReason.setVisibility(View.GONE);
				holder.textViewReason.setText("");
			} else if (attendList.get(position).check.equals("1")) {
				holder.student_name.setTextColor(0xff58595b);
				holder.linearLayout.setBackgroundResource(R.drawable.attenditem_true);
				holder.newcheck.setBackgroundResource(R.drawable.check_off);
				holder.textViewReason.setVisibility(View.VISIBLE);
				holder.textViewReason.setText("결석사유:"+attendList.get(pos).reason);
			}			
			
			holder.newcheck.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					FK_Stu_Att_Code = attendList.get(pos).PK_Stu_Code;
					chang_pos = pos;
					//최초 사유 기입. 바로 출석으로.
					if (attendList.get(pos).check.equals("null")) {
						startNetwork(ATTEND_INSERT_THREAD);

						//출석->결석, 사유기입.
					} else if (attendList.get(pos).check.equals("0")){
						AlertDialog.Builder alert = new AlertDialog.Builder(CalendarAttendListActivity.this);
						alert.setTitle("결석사유");
						alert.setMessage("결석하는 사유를 적어주세요.");
						final EditText input = new EditText(CalendarAttendListActivity.this);
						alert.setView(input);

						alert.setPositiveButton("Ok",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										Att_Reason = input.getText().toString();
										Att_Check = "1";
										startNetwork(ATTEND_CHANGE_THREAD);
									}
								});

						alert.setNegativeButton("Cancel",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										// Canceled.
									}
								});

						alert.show();						
						
						//결석->출석, 확인창만.	
					} else if (attendList.get(pos).check.equals("1")) {
						Att_Check = "0";
						Att_Reason ="출석";
						alertDialog("출결을 변경 하시겠습니까?", ATTEND_CHANGE_THREAD);
						
					}
				}
			});
			return convertView;
		}
	}

	class Calendar_Attend_List_Holder {
		TextView student_name;
		WebView image;
		ImageView newcheck;
		LinearLayout linearLayout;
		TextView textViewReason;
	}
/*	
//스피너에 반별 보기(원장님)	
	class Calendar_Spinner_List_Adapter extends ArrayAdapter<String> {
		
		public Calendar_Spinner_List_Adapter() {
			super(CalendarAttendListActivity.this, 0);
		}
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return classNameList.size();
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			Calendar_Spinner_List_Holder holder;
			final int pos1 = position;
			if (convertView == null) {
				convertView = CalendarAttendListActivity.this.getLayoutInflater()
						.inflate(R.layout.overflowitem_row, null);
				holder = new Calendar_Spinner_List_Holder();
				holder.school_name = (TextView) convertView.findViewById(R.id.OVERFLOWITEM_TV);
				holder.linearLayout = (LinearLayout) convertView.findViewById(R.id.CALENDAR_ATTEND_LIST_ROW_LL);
				convertView.setTag(holder);
			} else {
				holder = (Calendar_Spinner_List_Holder) convertView.getTag();
			}
			//반 이름.
			holder.school_name.setText(classNameList.get(position).Cla_Name);

			
			holder.school_name.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					choice_class = classNameList.get(pos1).PK_Cla_Code;
					startNetwork(SPINNER_LIST_THREAD);
				}
			});
			return convertView;
		}
	}
	
	class Calendar_Spinner_List_Holder {
		TextView school_name;
		LinearLayout linearLayout;
	}
	*/
	
//이미지 설정
	public String creHtmlBody(String imagUrl) {
		StringBuffer sb = new StringBuffer("<HTML>");
		sb.append("<HEAD>");
		sb.append("</HEAD>");
		sb.append("<BODY  style='margin: 0; padding: 0'>");
		sb.append("<img width=\"100%\" height=\"100%\" src=\"" + imagUrl
				+ "\">");
		sb.append("</BODY>");
		sb.append("</HTML>");

		return sb.toString();
	}

	// 네.아니오.선택다이얼로그
	void alertDialog(String string_title, int int_code) {
		final String title = string_title;
		final int code = int_code;
		AlertDialog.Builder builder = new AlertDialog.Builder(
				CalendarAttendListActivity.this);
		AlertDialog alert;
		builder.setMessage(title)
				.setCancelable(false)
				.setPositiveButton("네", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						startNetwork(code);
					}
				})
				.setNegativeButton("아니오",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.cancel();
							}
						});
		alert = builder.create();
		alert.show();
	}

	//뒤로 눌렀을때 새로고침.
@Override
public void onBackPressed() {
	//super.onBackPressed();
	alertDialogSetResult("출석체크를 종료하겠습니까?", REFRESH_CODE);

}
// 네.아니오.선택다이얼로그
void alertDialogSetResult(String string_title, int int_code) {
	final String title = string_title;
	final int code = int_code;
	AlertDialog.Builder builder = new AlertDialog.Builder(
			CalendarAttendListActivity.this);
	AlertDialog alert;
	builder.setMessage(title)
			.setCancelable(false)
			.setPositiveButton("네", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					setResult(code);
					finish();
				}
			})
			.setNegativeButton("아니오",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog,
								int which) {
							dialog.cancel();
						}
					});
	alert = builder.create();
	alert.show();
}
}
